import Dictionary = laya.utils.Dictionary;
/**
 * 本地 数据 管理器
 * Created by 杨乐 on 2017/5/15.
 */
class LocalDataManager{
    private static _instance:LocalDataManager;//单例
    private _sheetVoDic:Dictionary;//表 数据vo
    private _urlInitMap:Object = {};//字节url 是否存在

    constructor(){
        this._sheetVoDic = new Dictionary();
    }

    /**
     * 获取 本地数据管理器 单例
     */
    public static getInstance():LocalDataManager{
        if(LocalDataManager._instance == null){
            LocalDataManager._instance = new LocalDataManager();
        }
        return LocalDataManager._instance;
    }

    /**
     * 添加 本地数据
     * @param name 数据文件名
     */
    public addLocolData(name:string):void{
        var url:string = "data/" + name + ".bin";
        if(this._urlInitMap[url] == ""){
            return;
        }
        var buffer:ArrayBuffer = Laya.Loader.getRes(url);
        if(buffer == null){
            console.log(url + "没有加载");
            return;
        }
        this._urlInitMap[url] = "";
        var byteArray:ByteArray = new ByteArray(buffer);
        //解析
        byteArray.pos = 0;
        var sheetVo:LocalSheetVo;
        var readPos:number = 0;
        var sheetLen:number = 0;
        do{
            sheetLen = byteArray.readInt();
            readPos += 4;
            sheetVo = new LocalSheetVo(byteArray,readPos);
            this._sheetVoDic[sheetVo.fullPath] = sheetVo;
            readPos += sheetLen;
            byteArray.pos = readPos;
        }while(readPos != byteArray.length);
    }

    /**
     * 获取 vo列表 根据 表完整路径
     * @param fullPath
     * @return
     */
    public getVoListByPath(fullPath:string):Array<any>{
        var sheetVo:LocalSheetVo = this._sheetVoDic[fullPath];
        if(sheetVo == null){
            throw new Error(fullPath);
        }
        return sheetVo.voList;
    }

    /**
     * 获取 vo数据 根据  表完整路径 和 主键_副键
     * @param fullPath
     * @param key
     * @return
     */
    public getVoByValueName(fullPath:string,key:string):any{
        var sheetVo:LocalSheetVo = this._sheetVoDic[fullPath];
        return sheetVo.getClassVo(key);
    }
}